package me.lensfrex.doubandps.utils;

import java.io.*;
import java.nio.charset.Charset;

public class IOUtil {
    public static String inputStreamToString(InputStream inputStream, Charset charSet) throws IOException {
        return new String(readDataFromInputStream(inputStream), charSet);
    }

    public static byte[] readDataFromInputStream(InputStream inputStream) throws IOException {
        return readDataFromInputStream(inputStream, 5);// read every 5kb in default
    }

    public static byte[] readDataFromInputStream(InputStream inputStream, int byteAllocation) throws IOException {
        ByteArrayOutputStream byteArrayInputStream = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024 * byteAllocation];

        for (int length; (length = inputStream.read(bytes)) != -1; ) {
            byteArrayInputStream.write(bytes, 0, length);
        }

        byteArrayInputStream.flush();

        inputStream.close();
        byteArrayInputStream.close();

        return byteArrayInputStream.toByteArray();
    }

    public static byte[] getFileData(String path) throws IOException {
        return readDataFromInputStream(new FileInputStream(path));
    }

    public static void writeFile(byte[] bytes, File file) throws Exception {
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(bytes);
        fileOutputStream.close();
    }
}
